import cv2
import numpy as np
import time
from utils import capture_screenshot
from datetime import datetime
from settings import is_tianen, is_niu, is_daiyu, is_chelun, is_wang, is_fa
from seal import find_seal

template_fa = cv2.imread("images/option/fa.png", cv2.IMREAD_COLOR)
template_niu = cv2.imread("images/option/niu.png", cv2.IMREAD_COLOR)
template_daiyu = cv2.imread("images/option/daiyu.png", cv2.IMREAD_COLOR)
template_chelun = cv2.imread("images/option/chelun.png", cv2.IMREAD_COLOR)
template_wang = cv2.imread("images/option/wang.png", cv2.IMREAD_COLOR)

# 定义模板、名称和判断条件的映射列表，调整顺序与原代码一致
template_info = [
    (template_chelun, "chelun", is_chelun),
    (template_fa, "fa", is_fa),
    (template_daiyu, "daiyu", is_daiyu),
    (template_wang, "wang", is_wang),
    (template_niu, "niu", is_niu)
]

template_wan = cv2.imread("images/option/wan.png", cv2.IMREAD_COLOR)
template_gaizao = cv2.imread("images/option/gaizao.png", cv2.IMREAD_COLOR)
template_tianen = cv2.imread("images/option/tianen.png", cv2.IMREAD_COLOR)
template_tianen_p = cv2.imread("images/option/tianen_p.png", cv2.IMREAD_COLOR)
template_han = cv2.imread("images/option/han.png", cv2.IMREAD_COLOR)
template_han_p = cv2.imread("images/option/han_p.png", cv2.IMREAD_COLOR)
template_baiye = cv2.imread("images/option/baiye.png", cv2.IMREAD_COLOR)
template_baiye_p = cv2.imread("images/option/baiye_p.png", cv2.IMREAD_COLOR)
template_mojing = cv2.imread("images/option/mojing.png", cv2.IMREAD_COLOR)
template_mojing_p = cv2.imread("images/option/mojing_p.png", cv2.IMREAD_COLOR)
template_faming = cv2.imread("images/option/faming.png", cv2.IMREAD_COLOR)
template_faming_p = cv2.imread("images/option/faming_p.png", cv2.IMREAD_COLOR)
template_baozhu = cv2.imread("images/option/baozhu.png", cv2.IMREAD_COLOR)
template_baozhu_p = cv2.imread("images/option/baozhu_p.png", cv2.IMREAD_COLOR)
template_youtong = cv2.imread("images/option/youtong.png", cv2.IMREAD_COLOR)
template_youtong_p = cv2.imread("images/option/youtong_p.png", cv2.IMREAD_COLOR)
template_chelun_p = cv2.imread("images/option/chelun_p.png", cv2.IMREAD_COLOR)
template_wanxiang_p = cv2.imread("images/option/wanxiang_p.png", cv2.IMREAD_COLOR)
template_laien_p = cv2.imread("images/option/laien_p.png", cv2.IMREAD_COLOR)
template_lanxing_p = cv2.imread("images/option/lanxing_p.png", cv2.IMREAD_COLOR)
template_qingchai_p = cv2.imread("images/option/qingchai_p.png", cv2.IMREAD_COLOR)
template_yunduo = cv2.imread("images/option/yunduo.png", cv2.IMREAD_COLOR)
template_yunduo_p = cv2.imread("images/option/yunduo_p.png", cv2.IMREAD_COLOR)

# 找万象留卡优先级
template_info_wan = [
    (template_wan, "wan", True),
    (template_gaizao, "gaizao", False),
    (template_baiye_p, "baiye_p", True),
    (template_baiye, "baiye", True),
    (template_tianen_p, "tianen_p", True),
    (template_tianen, "tianen", True),
    (template_han_p, "han_p", True),
    (template_han, "han", True),
    (template_mojing_p, "mojing_p", True),
    (template_mojing, "mojing", True),
    (template_faming_p, "faming_p", True),
    (template_faming, "faming", True),
    (template_baozhu_p, "baozhu_p", True),
    (template_baozhu, "baozhu", True),
    (template_youtong_p, "youtong_p", True),
    (template_youtong, "youtong", True),
    (template_chelun_p, "chelun_p", True),
]

template_fenshen = cv2.imread("images/option/fenshen.png", cv2.IMREAD_COLOR)
template_dashi = cv2.imread("images/option/dashi.png", cv2.IMREAD_COLOR)
template_suo = cv2.imread("images/option/suo.png", cv2.IMREAD_COLOR)
template_libao = cv2.imread("images/option/libao.png", cv2.IMREAD_COLOR)

# 邀请函保留的卡
template_info_han = [
    (template_wan, "wan", True),
    (template_tianen, "tianen", True),
    (template_fenshen, "fenshen", True),
    (template_baiye, "baiye", True),
    (template_dashi, "dashi", True),
    (template_suo, "suo", True),
    (template_libao, "libao", True),
]

# 找生命模板
template_info_shengming = [
    (template_tianen_p, "tianen_p", True),
    (template_mojing_p, "mojing_p", True),
    (template_baozhu_p, "baozhu_p", True),
    (template_wanxiang_p, "wanxiang_p", True),
    (template_laien_p, "laien_p", True),
    (template_lanxing_p, "lanxing_p", True),
    (template_qingchai_p, "qingchai_p", True),
    (template_yunduo, "yunduo", True),
    (template_yunduo_p, "yunduo_p", True),
]

def find_fa():
    image = capture_screenshot(region_name="外面的选项")
    numbers = []  # 若没有特殊需求，可传入空列表
    position, template_name = find_select_index_multi(image, template_info, numbers)
    return position, template_name

def find_wan():
    """
    找万象
    找到返回匹配位置和模板名称
    没钱了返回 (-1, None)
    找不到返回最贵的位置和 None
    """
    image = capture_screenshot(region_name="里面的选项")
    numbers = find_numbers(image)
    if numbers:
#         seal_names = find_seal()
#         for i, seal_name in enumerate(seal_names):
#             # 再生紫卡优先
#             if seal_name == "zai" and 0 <= i < len(numbers) and numbers[i] == 3:
#                 return i + 1, "zai_zi"
        position, template_name = find_select_index_multi(image, template_info_wan, numbers)
        if position > 0:
            return position, template_name
        max_num = max(numbers)
        max_index = numbers.index(max_num)
        return max_index + 1, None
    return -1, None

def find_options():
    """
    找万象
    返回包含三个位置的包信息整合数组，每个元素包含价值、印章和名称
    结构为: [
        {"value": 价值1, "seal": 印章1, "name": 名称1},
        {"value": 价值2, "seal": 印章2, "name": 名称2},
        {"value": 价值3, "seal": 印章3, "name": 名称3}
    ]
    若获取信息失败，返回空数组
    """
    try:
        # 获取选项区域截图
        image = capture_screenshot(region_name="里面的选项")

        # 获取三个数组信息
        numbers = find_numbers(image)  # 包的价值数组
        seal_names = find_seal()       # 包的印章数组
        option_names = find_option_names(image, template_info_shengming, numbers)  # 包的名称数组

        # 确保三个数组都是长度为3
        if len(numbers) != 3:
            numbers = numbers[:3] + [None]*(3 - len(numbers))
        if len(seal_names) != 3:
            seal_names = seal_names[:3] + [None]*(3 - len(seal_names))
        if len(option_names) != 3:
            option_names = option_names[:3] + [None]*(3 - len(option_names))

        # 整合三个数组信息
        integrated_info = []
        for i in range(3):
            integrated_info.append({
                "value": numbers[i],
                "seal": seal_names[i],
                "name": option_names[i]
            })

        return integrated_info

    except Exception as e:
        print(f"获取万象信息出错: {str(e)}")
        return []

def find_han():
    """
    邀请函升级后找万象
    """
    image = capture_screenshot(region_name="图鉴的选项")
    numbers = find_numbers(image)
    numbers = [1] + numbers + [1]
    _, template_name = find_select_index_multi(image, template_info_han, numbers)
    return template_name, numbers[1]

def find_numbers(image):
    """
    返回包的价值数组
    彩包3 金包2 蓝包1
    找不到则返回空
    :param image: 选项区的图片
    """
    # 固定的区域
    test_regions = [(198, 1, 10, 10), (671, 1, 10, 10), (850, 1, 10, 10)]

#     for (x, y, w, h) in test_regions:
#         # 在图片上绘制红色矩形框
#         cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
#     save_path = "images/option/base2_t.png"
#     cv2.imwrite(save_path, image)

    average_colors = []
    for (x, y, w, h) in test_regions:
        # 提取指定区域
        roi = image[y:y + h, x:x + w]
        # 计算该区域的平均颜色
        average_color = np.mean(roi, axis=(0, 1))
        average_colors.append(average_color)

    gold_color = np.array([31, 62, 93])
    blue_color = np.array([99, 76, 58])
    purple_color = np.array([132, 85, 94])
    error_margin = 10  # 误差余量

    numbers = []
    for color in average_colors:
        if np.all(np.abs(color - gold_color) <= error_margin):
            numbers.append(2)
        elif np.all(np.abs(color - purple_color) <= error_margin):
            numbers.append(3)
        elif np.all(np.abs(color - blue_color) <= error_margin):
            numbers.append(1)
    return numbers

def find_select_index(image, template, numbers):
    """
    选项截图中指定模板的位置
    返回1、2、3
    找不到则返回0
    :param image: 选项区的图片
    :param template: 模板
    """
    # 固定的区域
    test_regions = [(0, 0, 127, 39), (469, 0, 127, 39), (937, 0, 127, 39)]

    for i, (x, y, w, h) in enumerate(test_regions):
        # 提取指定区域
        roi = image[y:y + h, x:x + w]
        result = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
        # print(f"第 {i + 1} 个位置相似度: {max_val}")
        # 获取当前时间
        if numbers and 0 <= i < len(numbers) and numbers[i] == 3:
            now = datetime.now()
            current_time_str = now.strftime("%Y%m%d%H%M%S")
            save_path = f"images/option/tem/{current_time_str}_{i + 1}.png"
            cv2.imwrite(save_path, roi)
#             print(f"已保存处理后的第 {i + 1} 张图片: {save_path}")
        if max_val > 0.7:
            return i + 1
    return 0

def find_select_index_multi(image, template_info, numbers):
    """
    选项截图中指定模板的位置
    返回匹配的位置（1、2、3）和模板名称
    找不到则返回 (0, None)
    :param image: 选项区的图片
    :param template_info: 模板信息列表，每个元素为 (模板, 模板名称, 开关条件)
    :param numbers: 用于控制保存图片的参数
    """
    # 固定的区域
    test_regions = [(0, 0, 127, 39), (469, 0, 127, 39), (937, 0, 127, 39)]
    # 提前提取指定区域
    rois = []
    for i, (x, y, w, h) in enumerate(test_regions):
        roi = image[y:y + h, x:x + w]
        rois.append(roi)
        # 根据 numbers 数组判断是否保存图片
        if numbers and 0 <= i < len(numbers) and numbers[i] == 3:
            now = datetime.now()
            current_time_str = now.strftime("%Y%m%d%H%M%S")
            save_path = f"images/option/tem/{current_time_str}_{i + 1}.png"
            cv2.imwrite(save_path, roi)

    # 根据开关条件筛选模板
    valid_templates = [(name, template) for template, name, condition in template_info if condition]

    for template_name, template in valid_templates:
        for i, roi in enumerate(rois):
            result = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED)
            min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
            if max_val > 0.7:
                return i + 1, template_name
    return 0, None

def find_option_names(image, template_info, numbers):
    """
    选项截图中指定模板的位置
    返回三个位置匹配到的模板名称数组，未匹配到的用None填充
    :param image: 选项区的图片
    :param template_info: 模板信息列表，每个元素为 (模板, 模板名称, 开关条件)
    :param numbers: 用于控制保存图片的参数
    """
    # 固定的三个区域
    test_regions = [(0, 0, 127, 39), (469, 0, 127, 39), (937, 0, 127, 39)]
    # 初始化结果数组，三个位置都先设为None
    result_array = [None, None, None]

    # 提前提取指定区域
    rois = []
    for i, (x, y, w, h) in enumerate(test_regions):
        roi = image[y:y + h, x:x + w]
        rois.append(roi)
        # 根据 numbers 数组判断是否保存图片
        if numbers and 0 <= i < len(numbers) and numbers[i] == 3:
            now = datetime.now()
            current_time_str = now.strftime("%Y%m%d%H%M%S")
            save_path = f"images/option/tem/{current_time_str}_{i + 1}.png"
            cv2.imwrite(save_path, roi)

    # 根据开关条件筛选模板
    valid_templates = [(name, template) for template, name, condition in template_info if condition]

    # 遍历每个区域
    for i, roi in enumerate(rois):
        # 检查该区域是否匹配任何有效模板
        for template_name, template in valid_templates:
            result = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED)
            min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
            if max_val > 0.7:
                # 找到匹配的模板，记录名称并跳出当前区域的模板检查
                result_array[i] = template_name
                break  # 一个区域只匹配一个模板

    return result_array

def create_template():
    """
    点开图鉴，制作模板
    """
    image = capture_screenshot(region_name="图鉴的选项")
    # 固定的区域
    test_regions = [(468, 0, 127, 39)]

    for i, (x, y, w, h) in enumerate(test_regions):
        # 提取指定区域
        roi = image[y:y + h, x:x + w]
        save_path = f"images/option/mojing_p.png"
        cv2.imwrite(save_path, roi)
        print(f"模板已保存到 {save_path}")

if __name__ == "__main__":
#     test_save_path = "images/option/tem2/20250311194601_3.png"
#     image = cv2.imread(test_save_path)
#     test_save_path2 = "images/option/han_p.png"
#     image2 = cv2.imread(test_save_path2)
#     result = cv2.matchTemplate(image, image2, cv2.TM_CCOEFF_NORMED)
#     min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
#     print(f"相似度: {max_val}")
#     name = find_options()
#     print(name)
    create_template()

